package com.autoglm.android.core.accessibility

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.Image
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.Surface
import android.view.WindowManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 屏幕截图捕获服务，负责获取屏幕内容
 */
class ScreenCaptureService(private val context: Context) {
    
    companion object {
        private const val TAG = "ScreenCaptureService"
        private const val VIRTUAL_DISPLAY_NAME = "AutoGLM_Screen_Capture"
    }
    
    private var mediaProjection: MediaProjection? = null
    private var virtualDisplay: VirtualDisplay? = null
    private var imageReader: ImageReader? = null
    private var width: Int = 0
    private var height: Int = 0
    private var density: Int = 0
    private val mainHandler = Handler(Looper.getMainLooper())
    
    // 截图状态流
    private val _captureState = MutableStateFlow<CaptureState>(CaptureState.Idle)
    val captureState: StateFlow<CaptureState> = _captureState.asStateFlow()
    
    init {
        // 获取屏幕尺寸
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val metrics = DisplayMetrics()
        wm.defaultDisplay.getMetrics(metrics)
        width = metrics.widthPixels
        height = metrics.heightPixels
        density = metrics.densityDpi
    }
    
    /**
     * 启动屏幕捕获
     * 
     * @param resultCode 权限请求结果码
     * @param data 权限请求返回的Intent
     */
    fun startCapture(resultCode: Int, data: Intent) {
        try {
            val projectionManager = context.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
            mediaProjection = projectionManager.getMediaProjection(resultCode, data)
            setupVirtualDisplay()
            
            _captureState.value = CaptureState.Ready
            Log.d(TAG, "Screen capture service started")
        } catch (e: Exception) {
            Log.e(TAG, "Failed to start screen capture", e)
            _captureState.value = CaptureState.Error("无法启动屏幕捕获: ${e.message}")
        }
    }
    
    /**
     * 设置虚拟显示
     */
    private fun setupVirtualDisplay() {
        // 配置ImageReader
        imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2)
        
        // 创建虚拟显示
        virtualDisplay = mediaProjection?.createVirtualDisplay(
            VIRTUAL_DISPLAY_NAME,
            width,
            height,
            density,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            imageReader?.surface,
            null,
            mainHandler
        )
    }
    
    /**
     * 捕获屏幕截图
     * 
     * @return 屏幕截图位图
     */
    suspend fun captureScreenshot(): Bitmap? = withContext(Dispatchers.IO) {
        try {
            _captureState.value = CaptureState.Capturing
            
            // 检查服务是否准备好
            if (mediaProjection == null || imageReader == null) {
                _captureState.value = CaptureState.Error("屏幕捕获服务未初始化")
                return@withContext null
            }
            
            // 获取图像
            var image: Image? = null
            try {
                image = imageReader?.acquireLatestImage()
                
                if (image == null) {
                    Log.w(TAG, "Failed to acquire image")
                    _captureState.value = CaptureState.Error("无法获取屏幕图像")
                    return@withContext null
                }
                
        // 获取屏幕信息
        val displayMetrics = context.resources.displayMetrics
        screenWidth = displayMetrics.widthPixels
        screenHeight = displayMetrics.heightPixels
        screenDensity = displayMetrics.densityDpi
        
        // 创建MediaProjection
        val projectionManager = context.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        mediaProjection = projectionManager.getMediaProjection(resultCode, data)
        
        // 创建ImageReader
        imageReader = ImageReader.newInstance(
            screenWidth, screenHeight, PixelFormat.RGBA_8888, 2
        ).apply {
            setOnImageAvailableListener({ /* 暂不处理 */ }, handler)
        }
        
        // 创建VirtualDisplay
        virtualDisplay = mediaProjection?.createVirtualDisplay(
            "ScreenCapture",
            screenWidth, screenHeight, screenDensity,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            imageReader?.surface, null, handler
        )
    }
    
    /**
     * 停止屏幕捕获
     */
    fun stopCapture() {
        virtualDisplay?.release()
        imageReader?.close()
        mediaProjection?.stop()
        
        virtualDisplay = null
        imageReader = null
        mediaProjection = null
    }
    
    /**
     * 捕获当前屏幕
     * @return 屏幕截图，如果失败则返回null
     */
    suspend fun captureScreen(): Bitmap? = withContext(Dispatchers.IO) {
        if (imageReader == null) {
            return@withContext null
        }
        
        var bitmap: Bitmap? = null
        var image: Image? = null
        
        try {
            // 获取最新的图像
            image = imageReader?.acquireLatestImage()
            if (image == null) {
                return@withContext null
            }
            
            // 转换为Bitmap
            val planes = image.planes
            val buffer = planes[0].buffer
            val pixelStride = planes[0].pixelStride
            val rowStride = planes[0].rowStride
            val rowPadding = rowStride - pixelStride * screenWidth
            
            bitmap = Bitmap.createBitmap(
                screenWidth + rowPadding / pixelStride,
                screenHeight,
                Bitmap.Config.ARGB_8888
            )
            
            bitmap.copyPixelsFromBuffer(buffer)
            
            // 裁剪到正确的尺寸
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, screenWidth, screenHeight)
        } catch (e: Exception) {
            bitmap = null
        } finally {
            image?.close()
        }
        
        return@withContext bitmap
    }
    
    /**
     * 请求媒体投影权限（在Activity中调用）
     * @param activity 用于启动权限请求的Activity
     * @param requestCode 请求码
     */
    fun requestMediaProjectionPermission(activity: Activity, requestCode: Int) {
        val projectionManager = activity.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        activity.startActivityForResult(projectionManager.createScreenCaptureIntent(), requestCode)
    }
} 